package com.example.module_motocircle.ui.search.adatpter

import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.flow_eventbus.post.postEvent
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.FragmentSearchSuggestionsBinding
import com.example.module_motocircle.databinding.LayoutSearchSuggestionItemBinding
import com.example.module_motocircle.model.SearchSuggestionModel
import com.example.module_motocircle.ui.search.SearchViewModel


class SearchSuggestionsFragment : BaseFragment<SearchViewModel, FragmentSearchSuggestionsBinding>() {

    companion object {
        val TAG: String = SearchSuggestionsFragment::class.java.simpleName
        private const val ONLY_TOPIC = "only_topic"
        fun newInstance(onlyTopic: Boolean): SearchSuggestionsFragment {
            val args = Bundle()
            args.putBoolean(ONLY_TOPIC, onlyTopic)
            val fragment = SearchSuggestionsFragment()
            fragment.arguments = args
            return fragment
        }//用于创建 SearchSuggestionsFragment 实例并传递参数
    }

    override val mLayoutResId: Int = R.layout.fragment_search_suggestions

     val mViewModel: SearchViewModel by activityViewModels()

    private var mOnlyTopic: Boolean = false

    private val mAdapter by lazy {
        SearchSuggestionAdapter {
            postEvent(SearchSuggestionEvent(it))
        }
    }

    override fun initView() {
        mOnlyTopic = arguments?.getBoolean(ONLY_TOPIC) ?: false
        initAdapter()
    }

    private fun initAdapter() {
        mBinding.rvSuggestion.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
        mBinding.rvSuggestion.adapter = mAdapter
    }

    override fun initListener() {

    }

    override fun initData() {

    }

    fun setNewData(list: List<SearchSuggestionModel>) {
        if (mOnlyTopic) {
            //mAdapter.setNewData(list.filter { it.socialType == MySocialConfig.TOPIC })
            mAdapter.setNewData(list)
        } else {
            mAdapter.setNewData(list)

        }

    }

    fun clearData() {
        mAdapter.clearData()
    }


    fun getFragmentParentView() = mParentView

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) {
            setNewData(listOf())
        }
    }

    /**请求状态*/
    fun onLoading() {
        mBinding.tvHint.visibility = View.VISIBLE
        mBinding.lEmpty.visibility = View.GONE
        mBinding.tvHint.text = "搜索中..."
    }

    fun onSuccess(keyword: String) {
        mAdapter.setHighlightWord(keyword)
        mBinding.tvHint.visibility = View.GONE
        mBinding.lEmpty.visibility = View.GONE
        mBinding.tvHint.text = ""
    }

    fun onError(msg: String) {
        mBinding.tvHint.visibility = View.GONE
        mBinding.lEmpty.visibility = View.VISIBLE
        mBinding.tvErrorViewHint.text = msg
    }

    class SearchSuggestionAdapter(private val onClickSuggestionItem: (SearchSuggestionModel) -> Unit) :
        RecyclerView.Adapter<SearchSuggestionViewHolder>() {
        private val suggestionList: MutableList<SearchSuggestionModel> = mutableListOf()
        private lateinit var mContext: Context
        private var highlightWord: String = ""

        fun setNewData(suggestionList: List<SearchSuggestionModel>) {
            this.suggestionList.clear()
            this.suggestionList.addAll(suggestionList)
            notifyDataSetChanged()
        }

        fun clearData() {
            this.suggestionList.clear()
            notifyDataSetChanged()
        }

        fun setHighlightWord(keyword: String) {
            this.highlightWord = keyword
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchSuggestionViewHolder {
            mContext = parent.context
            val binding = DataBindingUtil.inflate<LayoutSearchSuggestionItemBinding>(LayoutInflater.from(mContext), R.layout.layout_search_suggestion_item, parent, false)
            return SearchSuggestionViewHolder(binding)
        }

        override fun onBindViewHolder(holder: SearchSuggestionViewHolder, position: Int) {
            val suggestionItem = suggestionList[position]
            if (suggestionItem.socialType == MySocialConfig.TOPIC) {
                handleTopicSuggestion(holder, suggestionItem)
            } else {
                handleHighlightSuggestion(holder, suggestionItem)
            }
            holder.binding.root.setOnClickListener {
                onClickSuggestionItem.invoke(suggestionItem)
            }
        }


        //处理话题的搜索建议
        private fun handleTopicSuggestion(holder: SearchSuggestionViewHolder, suggestion: SearchSuggestionModel) {
            val content = String.format("#%s#", suggestion.keyword)
            val spannableStringBuilder = SpannableStringBuilder(content)
            spannableStringBuilder.setSpan(ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.topic)), 0, content.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            holder.binding.tv.text = spannableStringBuilder
        }

        //高亮处理
        private fun handleHighlightSuggestion(holder: SearchSuggestionViewHolder, suggestion: SearchSuggestionModel) {
            //holder.binding.tv.text = JTextUtils.highlight((suggestion.keyword?:"").toString().trim().replace("\r|\n", ""), highlightWord, ContextCompat.getColor(mContext, R.color.color_d8000f))
            holder.binding.tv.text = (suggestion.keyword ?: "").toString().trim().replace("\r|\n", "")
        }

        override fun getItemCount(): Int {
            return suggestionList.size
        }
    }

    class SearchSuggestionViewHolder(val binding: LayoutSearchSuggestionItemBinding) : RecyclerView.ViewHolder(binding.root)
}